package com.fqgj.xjd.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.exception.common.ApplicationException;
import com.fqgj.xjd.user.client.UserAadhaarService;
import com.fqgj.xjd.user.client.UserKycDocumentService;
import com.fqgj.xjd.user.client.enums.UserKycTypeEnum;
import com.fqgj.xjd.user.client.request.UserAadhaarScoreInfo;
import com.fqgj.xjd.user.client.request.UserAdvanceAadhaarVo;
import com.fqgj.xjd.user.client.response.*;
import com.fqgj.xjd.user.common.utils.DateUtil;
import com.fqgj.xjd.user.dao.UserAadhaarScoreDao;
import com.fqgj.xjd.user.dao.UserAuthAdvanceAadhaarDao;
import com.fqgj.xjd.user.dao.UserOcrAadhaarBackDao;
import com.fqgj.xjd.user.dao.UserOcrAadhaarFrontBottomDao;
import com.fqgj.xjd.user.entity.UserAuthAdvanceAadhaarEntity;
import com.fqgj.xjd.user.entity.UserOcrAadhaarBackEntity;
import com.fqgj.xjd.user.entity.UserOcrAadhaarFrontBottomEntity;
import com.fqgj.xjd.user.entity.business.UserAdahaarScoreEntity;
import com.fqgj.xjd.user.integration.UserOcrService;
import com.qianli.user.domain.enums.UserAuthStatusEnum;
import com.qianli.user.exception.UserException;
import com.qianli.user.ro.UserStateCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户Aadhaar信息服务
 */
@Service("userAadhaarService")
public class UserAadhaarServiceImpl implements UserAadhaarService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserAadhaarServiceImpl.class);
    @Autowired
    private UserOcrAadhaarBackDao userOcrAadhaarBackDao;
    @Autowired
    private UserOcrAadhaarFrontBottomDao userOcrAadhaarFrontBottomDao;
    @Autowired
    private UserOcrService userOcrService;
    @Autowired
    private UserKycDocumentService userKycDocumentService;
    @Autowired
    private UserAadhaarScoreDao userAadhaarScoreDao;
    @Autowired
    private UserAuthAdvanceAadhaarDao userAuthAdvanceAadhaarDao;

    @Override
    public Response<AadhaarBack> getAadhaarBackOcrByUserCode(String userCode) {
        if (StringUtils.isEmpty(userCode)) {
            throw new UserException(UserStateCode.PARAMETER_LACK);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userCode", userCode);
        map.put("deleted", "0");
        List<UserOcrAadhaarBackEntity> userOcrAadhaarBackEntities = userOcrAadhaarBackDao.selectByParams(map);
        AadhaarBack aadhaarBack = new AadhaarBack();
        //没有保存过ocr信息
        if (null == userOcrAadhaarBackEntities || userOcrAadhaarBackEntities.isEmpty() || !userOcrAadhaarBackEntities.get(0).getStatus().equals(UserAuthStatusEnum.AUTHORIZED.getStatus())) {
            //请求ocr接口获取数据
            UserKycDocumentInfo userKyc = getUserKycDocumentInfo(userCode);
            aadhaarBack = userOcrService.ocrForAadhaarBack(userKyc.getCardBackUrl());
//            logger.info("aadhaarback ocr info:{}", JSON.toJSONString(aadhaarBack));
            if (aadhaarBack == null) {
                return Response.ok(aadhaarBack);
            }
            //存储ocr信息
            UserOcrAadhaarBackEntity userOcrAadhaarBackEntity = new UserOcrAadhaarBackEntity();
            BeanUtils.copyProperties(aadhaarBack, userOcrAadhaarBackEntity);
            userOcrAadhaarBackEntity.setAddressSplit(JSON.toJSONString(aadhaarBack.getAddressSplit()));
            userOcrAadhaarBackEntity.setStatus(UserAuthStatusEnum.AUTHORIZED.getStatus());
            userOcrAadhaarBackEntity.setCount(1);
            userOcrAadhaarBackEntity.setUserCode(userCode);
            userOcrAadhaarBackDao.insert(userOcrAadhaarBackEntity);
        } else {
            UserOcrAadhaarBackEntity userOcrAadhaarBackEntity = userOcrAadhaarBackEntities.get(0);
            BeanUtils.copyProperties(userOcrAadhaarBackEntity, aadhaarBack);
            aadhaarBack.setAddressSplit(JSON.parseObject(userOcrAadhaarBackEntity.getAddressSplit(), AddressSplit.class));
        }
        return Response.ok(aadhaarBack);
    }

    private UserKycDocumentInfo getUserKycDocumentInfo(String userCode) {
        List<UserKycDocumentInfo> userKycDocumentInfos = Optional.ofNullable(userKycDocumentService.getByUserCode(userCode))
                .filter(Response::isSuccess).map(Response::getData).orElseThrow(UserException::new);
        if (CollectionUtils.isEmpty(userKycDocumentInfos)) {
            throw new UserException(UserStateCode.USER_NOT_EXITS);
        }
        return userKycDocumentInfos.stream()
                .filter(userKycDocumentInfo -> Objects.equals(UserKycTypeEnum.AADHAAR, userKycDocumentInfo.getAuthType()))
                .findFirst().orElseGet(UserKycDocumentInfo::new);
    }

    /**
     * 通过ocr扫描获取aadhaar正面底部信息
     *
     * @param userCode
     */
    @Override
    public Response<AadhaarFrontBottom> getAadhaarFrontBottomOcrByUserCode(String userCode) {
        if (StringUtils.isEmpty(userCode)) {
            throw new UserException(UserStateCode.PARAMETER_LACK);
        }
        Map<String, Object> map = new HashMap<>(1);
        map.put("userCode", userCode);
        map.put("deleted", "0");
        List<UserOcrAadhaarFrontBottomEntity> userOcrAadhaarFrontBottomEntities = userOcrAadhaarFrontBottomDao.selectByParams(map);
        AadhaarFrontBottom aadhaarFrontBottom = new AadhaarFrontBottom();
        //没有保存过ocr信息
        if (null == userOcrAadhaarFrontBottomEntities || userOcrAadhaarFrontBottomEntities.isEmpty() || !userOcrAadhaarFrontBottomEntities.get(0).getStatus().equals(UserAuthStatusEnum.AUTHORIZED.getStatus())) {
            //请求ocr接口获取数据
            UserKycDocumentInfo userKyc = getUserKycDocumentInfo(userCode);
            aadhaarFrontBottom = userOcrService.ocrForAadhaarFrontBottom(userKyc.getCardFrontUrl());
//            logger.info("aadhaarfrontbottom ocr info:{}", JSON.toJSONString(aadhaarFrontBottom));
            if (aadhaarFrontBottom == null) {
                return Response.ok(aadhaarFrontBottom);
            }
            //存储ocr信息
            UserOcrAadhaarFrontBottomEntity userOcrAadhaarFrontBottomEntity = new UserOcrAadhaarFrontBottomEntity();
            BeanUtils.copyProperties(aadhaarFrontBottom, userOcrAadhaarFrontBottomEntity);
            userOcrAadhaarFrontBottomEntity.setStatus(UserAuthStatusEnum.AUTHORIZED.getStatus());
            userOcrAadhaarFrontBottomEntity.setCount(1);
            userOcrAadhaarFrontBottomEntity.setUserCode(userCode);
            userOcrAadhaarFrontBottomDao.insert(userOcrAadhaarFrontBottomEntity);
        } else {
            UserOcrAadhaarFrontBottomEntity userOcrAadhaarBackEntity = userOcrAadhaarFrontBottomEntities.get(0);
            BeanUtils.copyProperties(userOcrAadhaarBackEntity, aadhaarFrontBottom);
        }
        return Response.ok(aadhaarFrontBottom);
    }

    /**
     * 移除ocr扫描aadhaar背面信息
     */
    @Override
    public Response removeAadhaarBackOcrInfo(String userCode) {
        userOcrAadhaarBackDao.deleteByUserCode(userCode);
        return Response.ok();
    }

    /**
     * 移除ocr扫描aadhaar正面底部信息
     */
    @Override
    public Response removeAadhaarFrontBottomOcrInfo(String userCode) {
        userOcrAadhaarFrontBottomDao.deleteByUserCode(userCode);
        return Response.ok();
    }

    private UserAadhaarInfo getUserAadhaarInfo(UserAadhaarInfo userAadhaarInfo) {
        String cardFrontUrl = userAadhaarInfo.getCardFrontUrl();
        if (StringUtils.isNotBlank(cardFrontUrl) && cardFrontUrl.contains("cashmama-pro")) {
            cardFrontUrl = cardFrontUrl.replace("cashmama-pro.", "");
        }
        userAadhaarInfo.setCardFrontUrl(cardFrontUrl);

        String backUrl = userAadhaarInfo.getCardBackUrl();
        if (StringUtils.isNotBlank(backUrl) && backUrl.contains("cashmama-pro")) {
            backUrl = backUrl.replace("cashmama-pro.", "");
        }
        userAadhaarInfo.setCardBackUrl(backUrl);

        String selfieUrl = userAadhaarInfo.getSelfieUrl();
        if (StringUtils.isNotBlank(selfieUrl) && selfieUrl.contains("cashmama-pro")) {
            selfieUrl = selfieUrl.replace("cashmama-pro.", "");
        }
        userAadhaarInfo.setSelfieUrl(selfieUrl);

        String handheldUrl = userAadhaarInfo.getHandheldUrl();
        if (StringUtils.isNotBlank(handheldUrl) && handheldUrl.contains("cashmama-pro")) {
            handheldUrl = handheldUrl.replace("cashmama-pro.", "");
        }
        userAadhaarInfo.setHandheldUrl(handheldUrl);

        return userAadhaarInfo;
    }

    @Override
    public Response saveAadhaarScoreInfo(UserAadhaarScoreInfo userAadhaarScoreInfo) {
        // 用户eq详细信息入库

        LOGGER.info("equifax存储详细信息：" + JSONObject.toJSONString(userAadhaarScoreInfo));
        UserAdahaarScoreEntity userAdahaarScoreEntity = new UserAdahaarScoreEntity();
        userAdahaarScoreEntity.setUserCode(userAadhaarScoreInfo.getUserCode());
        userAdahaarScoreEntity.setScore(userAadhaarScoreInfo.getScore());
        userAdahaarScoreEntity.setReportUrl(userAadhaarScoreInfo.getReportUrl());
        userAdahaarScoreEntity.setSuccess(userAadhaarScoreInfo.getSuccess());
        userAadhaarScoreDao.insert(userAdahaarScoreEntity);

        return Response.ok();
    }

    @Override
    public Response getAadhaarScoreByUserCode(String userCode) {

        UserAdahaarScoreEntity entity = userAadhaarScoreDao.getAadhaarEntityByUserCode(userCode);

        if (entity == null) {
//            logger.info("=====查询数据为空，userCode:{}", userCode);

            return Response.ok().putData(null);
        }
        Date creatDate = entity.getGmtCreate();
        int diffDays = DateUtil.differentDays(creatDate, new Date());
        boolean isEffective = true;
        if (diffDays > 30) {

            isEffective = false;
        }

        AadhaarScoreInfo aadhaarScoreInfo = new AadhaarScoreInfo();
        aadhaarScoreInfo.setUserCode(userCode);
        aadhaarScoreInfo.setScore(entity.getScore());
        aadhaarScoreInfo.setReportUrl(entity.getReportUrl());
        aadhaarScoreInfo.setEffective(isEffective);
//        logger.info("=====返回数据，userCode:{}", userCode);

        return Response.ok().putData(aadhaarScoreInfo);
    }

    @Override
    public Response<UserAdvanceAadhaarVo> addUserAdvanceAadhaar(UserAdvanceAadhaarVo userAdvanceAadhaarVo) {
        if (StringUtils.isEmpty(userAdvanceAadhaarVo.getUserCode()) || StringUtils.isEmpty(userAdvanceAadhaarVo.getAadhaarNo())) {
            throw new ApplicationException("AadhaarNo is empty!");
        }
        UserAuthAdvanceAadhaarEntity entity = userAuthAdvanceAadhaarDao.selectLastUserAuthAdvanceAadhaar(userAdvanceAadhaarVo.getUserCode());
        if (entity == null) {
            entity = new UserAuthAdvanceAadhaarEntity();
            BeanUtils.copyProperties(userAdvanceAadhaarVo, entity);
            userAuthAdvanceAadhaarDao.insert(entity);
        } else {
            entity.setUserCode(userAdvanceAadhaarVo.getUserCode());
            entity.setAadhaarNo(userAdvanceAadhaarVo.getAadhaarNo());
            entity.setStatus(userAdvanceAadhaarVo.getStatus());
            entity.setResult(userAdvanceAadhaarVo.getResult());
            userAuthAdvanceAadhaarDao.updateByPrimaryKey(entity);
        }
        return Response.ok().putData(userAdvanceAadhaarVo);
    }

    @Override
    public Response<UserAdvanceAadhaarVo> getUserAdvanceAadhaar(String userCode) {
        UserAuthAdvanceAadhaarEntity entity = userAuthAdvanceAadhaarDao.selectLastUserAuthAdvanceAadhaar(userCode);
        if (entity == null) {
            return Response.ok().putData(null);
        }
        UserAdvanceAadhaarVo advanceAadhaarVo = new UserAdvanceAadhaarVo();
        BeanUtils.copyProperties(entity, advanceAadhaarVo);
        return Response.ok().putData(advanceAadhaarVo);
    }
}
